package com.hzeport.bgs22emduty.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzeport.bgs22emduty.config.SystemConfig;
import com.hzeport.bgs22emduty.config.login.LoginCompoentService;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.dto.DutyScheduleInfoTimeDTO;
import com.hzeport.bgs22emduty.dto.ScreenCheckDTO;
import com.hzeport.bgs22emduty.dto.ScreenCheckDetailVO;
import com.hzeport.bgs22emduty.dto.ScreenCheckSaveDTO;
import com.hzeport.bgs22emduty.dto.screenCheck.*;
import com.hzeport.bgs22emduty.entity.*;
import com.hzeport.bgs22emduty.enums.DeleteFlagEnum;
import com.hzeport.bgs22emduty.enums.STypeEnum;
import com.hzeport.bgs22emduty.enums.SettingModeEnum;
import com.hzeport.bgs22emduty.outbound.*;
import com.hzeport.bgs22emduty.outbound.db.ScreenCheckRepositoryImpl;
import com.hzeport.bgs22emduty.service.DutyScheduleInfoService;
import com.hzeport.bgs22emduty.service.ScreenDutyCheckService;
import com.hzeport.bgs22emduty.service.SecurityLogService;
import com.hzeport.bgs22emduty.common.utils.IpUtils;
import com.hzeport.bgs22emduty.common.base.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * ${comments}
 *
 * @author code generator
 * @date 2023-02-14 09:39:44
 */
@Service
@Slf4j
public class ScreenCheckServiceImpl extends BaseServiceImpl<ScreenCheckRepositoryImpl, ScreenCheck> implements ScreenDutyCheckService {

    @Resource
    private ScreenCheckRepository screenCheckRepository;

    @Resource
    private LoginCompoentService loginCompoentService;

    @Resource
    private SystemConfig systemConfig;
    @Resource
    private ParamHolidaysRepository paramHolidaysRepository;
    @Resource
    private BasePersonInfoRepository basePersonInfoRepository;
    @Resource
    private BaseDeptInfoRepository baseDeptInfoRepository;
    @Resource
    private ParamDictionaryRepository paramDictionaryRepository;
    @Resource
    private DutyScheduleInfoService dutyScheduleInfoService;
    @Resource
    private ScreenSubCustomRepository screenSubCustomRepository;
    @Resource
    private DutyScheduleInfoRepository dutyScheduleInfoRepository;
    @Resource
    private BaseCustomPhoneRepositoy baseCustomPhoneRepositoy;
    @Resource
    private ScreenCheckReasonRepository screenCheckReasonRepository;
    @Resource
    private SecurityLogService securityLogService;
    @Resource
    private ScreenCheckDetailRepository screenCheckDetailRepository;
    @Resource
    private ScreenCheckTopicRepository screenCheckTopicRepository;

    @Override
    public Page<ScreenCheckDetailShowVO> page(ScreenCheckDTO dto) {
        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        LambdaQueryWrapper<ScreenCheck> queryWrapper = new LambdaQueryWrapper<>();
        ParamDictionary paramDictionary = paramDictionaryRepository.getOne(new LambdaQueryWrapper<ParamDictionary>()
                .eq(ParamDictionary::getParamModule, "ZBRY")
                .eq(ParamDictionary::getParamCode, "ZSGQ"), false);
        String customs = paramDictionary.getParamName();
        String[] customArray = customs.split(",");
        if (userInfoDetailVO.getRole().contains("ZGGLY")) {
            queryWrapper.in(ScreenCheck::getCustomName, Arrays.asList(customArray));
        } else {
            queryWrapper.eq(ScreenCheck::getCustomId, userInfoDetailVO.getCustomscode());
        }
        if (!CollectionUtils.isEmpty(dto.getTimes()) && StringUtils.isNotBlank(dto.getTimes().get(0))) {
            LocalDateTime startLocalDateTime = LocalDate.parse(dto.getTimes().get(0), DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay();
            queryWrapper.ge(ScreenCheck::getCheckTime, startLocalDateTime);
        }
        if (!CollectionUtils.isEmpty(dto.getTimes()) && StringUtils.isNotBlank(dto.getTimes().get(1))) {
            LocalDateTime endLocalDateTime = LocalDate.parse(dto.getTimes().get(1), DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay().plusDays(1);
            queryWrapper.le(ScreenCheck::getCheckTime, endLocalDateTime);
        }
        if (StringUtils.isNotBlank(dto.getCustomName())) {
            queryWrapper.eq(ScreenCheck::getCustomName, dto.getCustomName());
        }
        if (StringUtils.isNotBlank(dto.getCheckType())) {
            queryWrapper.eq(ScreenCheck::getCheckType, dto.getCheckType());
        }
        queryWrapper.eq(StringUtils.isNotBlank(dto.getReasonId()), ScreenCheck::getReasonId, dto.getReasonId());

        queryWrapper.orderByDesc(ScreenCheck::getCheckTime);
        Page<ScreenCheck> page = screenCheckRepository.page(new Page<>(dto.getPageNum(), dto.getPageSize()), queryWrapper);
        Page<ScreenCheckDetailShowVO> voPage = new Page<>();
        List<ScreenCheckDetailShowVO> screenCheckDetailVOS = page.getRecords().stream().map(i -> {
            if (i != null && !StringUtils.isEmpty(i.getDutyPerson())) {
                BasePersonInfo basePersonInfo = basePersonInfoRepository.getOne(new LambdaQueryWrapper<BasePersonInfo>()
                        .eq(BasePersonInfo::getUserno, i.getDutyPerson()));
                if (basePersonInfo != null) {
                    i.setDutyPerson(basePersonInfo.getUsername() + " " + i.getDutyPerson());
                }
            }
            if (i != null && i.getReasonId() != null) {
                ScreenCheckReason screenCheckReason = screenCheckReasonRepository.getById(i.getReasonId());
                if (screenCheckReason != null) {
                    i.setReason(screenCheckReason.getReason());
                }
            }
            List<ScreenCheckDetail> screenCheckDetails = screenCheckDetailRepository.list(
                    new LambdaQueryWrapper<ScreenCheckDetail>()
                            .eq(ScreenCheckDetail::getCheckId, i.getId())
                            .orderByAsc(ScreenCheckDetail::getSort));
            ScreenCheckDetailShowVO screenCheckDetailVO = new ScreenCheckDetailShowVO();
            BeanUtils.copyProperties(i, screenCheckDetailVO);
            List<ScreenCheckTopic> screenCheckQuestions = screenCheckTopicRepository.list(new LambdaQueryWrapper<ScreenCheckTopic>()
                    .eq(ScreenCheckTopic::getCustomId, userInfoDetailVO.getCustomscode())
                    .orderByAsc(ScreenCheckTopic::getSort));
            if (!CollectionUtils.isEmpty(screenCheckDetails)) {
                List<ScreenCheckDetailChildVO> checkDetailChildVOS = new ArrayList<>();
//               Map<String,String> screenCheckDetailsMap=screenCheckDetails.stream().collect(Collectors.toMap(ScreenCheckDetail::getQuestionTitle,ScreenCheckDetail::getResultValue));
                for (ScreenCheckDetail screenCheckTopic : screenCheckDetails) {
                    ScreenCheckDetailChildVO screenCheckDetailChildVO = new ScreenCheckDetailChildVO();
                    screenCheckDetailChildVO.setLabel(screenCheckTopic.getQuestionTitle());
                    screenCheckDetailChildVO.setValue(screenCheckTopic.getResultValue());
                    checkDetailChildVOS.add(screenCheckDetailChildVO);
                }
                screenCheckDetailVO.setChildren(checkDetailChildVOS);
            }
            return screenCheckDetailVO;
        }).collect(Collectors.toList());
        voPage.setRecords(screenCheckDetailVOS);
        voPage.setTotal(page.getTotal());
        return voPage;
    }


    /**
     * {"带班关领导":"1","带班处领导":"0","重大突发事件处理":"0","reasonId":"3166778788594565120","remark":"321"}
     *
     * @param param
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object update(JSONObject param) throws Exception {
//        ScreenCheck screenCheck1 = new ScreenCheck();
//        screenCheckRepository.updateById(screenCheck1);
//        return screenCheck1;
        ScreenCheck screenCheck = repository.getById(param.getString("id"));
        if (screenCheck == null) {
            throw new Exception("未取得id对应的抽查纪录");
        }
        String remark = param.getString("remark");
        String reasonId = param.getString("reasonId");
        screenCheck.setRemark(remark);
        screenCheck.setReasonId(reasonId);
        screenCheckRepository.updateById(screenCheck);

        List<ScreenCheckDetail> screenCheckDetails = new ArrayList<>();
        String customId = loginCompoentService.getUserInfo().getCustomscode();
        List<ScreenCheckTopic> screenCheckTopics = screenCheckTopicRepository
                .list(new LambdaQueryWrapper<ScreenCheckTopic>()
                        .eq(ScreenCheckTopic::getCustomId, customId));
        screenCheckDetailRepository.remove(new LambdaQueryWrapper<ScreenCheckDetail>()
                .eq(ScreenCheckDetail::getCheckId, screenCheck.getId()));
        for (String key : param.keySet()) {
            if (screenCheckTopics.stream().map(i -> i.getQuestionTitle()).collect(Collectors.toList()).contains(key)) {
                ScreenCheckDetail screenCheckDetail = new ScreenCheckDetail();
                screenCheckDetail.setQuestionTitle(key);
                screenCheckDetail.setDelFlag("0");
                screenCheckDetail.setCheckId(screenCheck.getId());
                screenCheckDetail.setResultValue(param.getString(key));
                screenCheckDetails.add(screenCheckDetail);
            }
        }
        screenCheckDetailRepository.saveBatch(screenCheckDetails);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object saveTwo(ScreenCheckSaveDTO screenCheckSaveDTO, HttpServletRequest request) throws Exception {
        String checkPerson = screenCheckSaveDTO.getScreenCheckList().get(0).getString("checkPerson");
        if (!StringUtils.isEmpty(checkPerson)) {
            BasePersonInfo basePersonInfo = basePersonInfoRepository.getOne(new LambdaQueryWrapper<BasePersonInfo>()
                    .eq(BasePersonInfo::getUserno, checkPerson));

        }
        List<ScreenCheck> screenChecks = new ArrayList<>();
        List<ScreenCheckDetail> screenCheckDetails = new ArrayList<>();
        for (JSONObject jsonObject : screenCheckSaveDTO.getScreenCheckList()) {
            ScreenCheck screenCheck = new ScreenCheck();
            ScreenCheckLSSaveDTO screenCheckLSSaveDTO = JSONObject.parseObject(jsonObject.toJSONString(), ScreenCheckLSSaveDTO.class);
            BeanUtils.copyProperties(screenCheckLSSaveDTO, screenCheck);
            screenCheck.setCheckPerson(jsonObject.getString("hzPersonName"));
            screenCheck.setCheckPersonNo(jsonObject.getString("hzPersonNo"));
            screenCheck.setCheckTime(LocalDateTime.now());
            screenCheck.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            screenCheck.setCreateTime(LocalDateTime.now());
            screenCheck.setCustomId(screenCheckSaveDTO.getCustomId());
            screenCheck.setUpdateTime(LocalDateTime.now());
            DutyScheduleInfoTimeDTO result = dutyScheduleInfoService.nowUser(screenCheck.getCustomName()).getData();
            if (result != null) {
                if (result.getCJInfo() != null && result.getCJInfo().getDUsername() != null) {
                    screenCheck.setCjName(result.getCJInfo().getDUsername());
                }
                if (result.getManagerInfo() != null && result.getManagerInfo().getDUsername() != null) {
                    screenCheck.setManagerName(result.getManagerInfo().getDUsername());
                }
            }
            screenCheck.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            screenCheck.setBatchNum("0");
            screenChecks.add(screenCheck);
            String customId = screenCheckSaveDTO.getCustomId();
            if (StringUtils.isEmpty(customId)) {
                customId = systemConfig.getZsCustomId();
            }
            List<ScreenCheckTopic> screenCheckTopics = screenCheckTopicRepository
                    .list(new LambdaQueryWrapper<ScreenCheckTopic>()
                            .eq(ScreenCheckTopic::getCustomId, customId));
            screenCheckDetailRepository.remove(new LambdaQueryWrapper<ScreenCheckDetail>()
                    .eq(ScreenCheckDetail::getCheckId, screenCheck.getId()));
            Map<String, Integer> stringMap = screenCheckTopics.stream().collect(Collectors.toMap(ScreenCheckTopic::getQuestionTitle, ScreenCheckTopic::getSort));
            for (String key : jsonObject.keySet()) {
                if (screenCheckTopics.stream().map(i -> i.getQuestionTitle().trim()
                        .replaceAll("\\t", "")).collect(Collectors.toList()).contains(key.trim()
                        .replaceAll("\\t", ""))) {
                    ScreenCheckDetail screenCheckDetail = new ScreenCheckDetail();
                    screenCheckDetail.setQuestionTitle(key);
                    screenCheckDetail.setDelFlag("0");
                    screenCheckDetail.setCheckId(screenCheck.getId());
                    screenCheckDetail.setResultValue(jsonObject.getString(key));
                    screenCheckDetail.setSort(stringMap.get(key.trim()
                            .replaceAll("\\t", "")));
                    screenCheckDetails.add(screenCheckDetail);
                }
            }
        }
        String customtId = screenCheckSaveDTO.getCustomId();
        if (customtId == null) {
            screenCheckRepository.update(new LambdaUpdateWrapper<ScreenCheck>()
                    .isNull(ScreenCheck::getCustomId)
                    .set(ScreenCheck::getUpdateTime, LocalDateTime.now())
                    .set(ScreenCheck::getBatchNum, "1")
                    .set(ScreenCheck::getUpdateBy, "sys"));
        }
        SecurityLog operateLog = new SecurityLog();
        operateLog.setCreateBy("");
        operateLog.setCreateTime(LocalDateTime.now());
        operateLog.setIpAddress(IpUtils.getIpAddr(request));
        operateLog.setSDescription(JSON.toJSONString(screenCheckSaveDTO));
        operateLog.setSModule("ZBCC");
        operateLog.setSTitle("CCBC");
        screenCheckRepository.saveBatch(screenChecks);
        screenCheckDetailRepository.saveBatch(screenCheckDetails);
        securityLogService.save(operateLog);
        return "保存成功";
    }

    @Override
    public Object getNextCustoms(String type, String customId) {
        List<BaseDeptInfo> baseDeptInfos;
        String customName = systemConfig.getZsCustomName();
        if (StringUtils.isEmpty(customId)) {
            ParamDictionary paramDictionary = paramDictionaryRepository.getOne(new LambdaQueryWrapper<ParamDictionary>()
                    .eq(ParamDictionary::getParamModule, "ZBRY")
                    .eq(ParamDictionary::getParamCode, "ZSGQ"), false);
            String customs = paramDictionary.getParamName();
            String[] customArray = customs.split(",");
            paramDictionary = paramDictionaryRepository.getOne(new LambdaQueryWrapper<ParamDictionary>()
                    .eq(ParamDictionary::getParamModule, "ZBRY")
                    .eq(ParamDictionary::getParamCode, "JCBMID"), false);
            baseDeptInfos = baseDeptInfoRepository.list(new LambdaQueryWrapper<BaseDeptInfo>()
                    .in(BaseDeptInfo::getDeptName, Arrays.asList(customArray))
                    .in(BaseDeptInfo::getParentid, paramDictionary.getParamName()));
        } else {
            BaseDeptInfo custom = baseDeptInfoRepository.getById(customId);
            customName = custom.getDeptName();
            List<ScreenSubCustom> screenSubCustoms = screenSubCustomRepository.list(
                    new LambdaQueryWrapper<ScreenSubCustom>()
                            .eq(ScreenSubCustom::getParentid, customId));
            baseDeptInfos = screenSubCustoms.stream().map(i -> {
                BaseDeptInfo baseDeptInfo = new BaseDeptInfo();
                BeanUtils.copyProperties(i, baseDeptInfo);
                return baseDeptInfo;
            }).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(baseDeptInfos)) {
            return new ArrayList<>();
        }
        if (!StringUtils.isEmpty(customId)) {
            Page<ScreenCheck> screenCheckList = screenCheckRepository
                    .page(new Page<>(1, 2), new LambdaQueryWrapper<ScreenCheck>().orderByDesc(ScreenCheck::getCheckTime));
            ParamDictionary paramDictionary = paramDictionaryRepository.getOne(new LambdaQueryWrapper<ParamDictionary>()
                    .eq(ParamDictionary::getParamModule, "ZBCC")
                    .eq(ParamDictionary::getParamCode, "GQSX"), false);
            String customs = paramDictionary.getParamName();
            String[] customArray = customs.split(",");
            baseDeptInfos = baseDeptInfos.stream().sorted(Comparator.comparingInt(i -> {
                return Arrays.asList(customArray).indexOf(i.getDeptName());
            })).collect(Collectors.toList());

        }
        if (!"2".equals(type)) {

            DutyScheduleInfoTimeDTO dutyScheduleInfoTimeDTO = dutyScheduleInfoService.nowUser(customName).getData();
            List<Integer> indexs = new ArrayList<>();
            Random random = new Random();
            if (baseDeptInfos.size() <= 3) {
                return getPersonForScreenCheck(baseDeptInfos, dutyScheduleInfoTimeDTO, customId);
            }
            while (indexs.size() < 3) {
                Integer index = random.nextInt(baseDeptInfos.size());
                if (!indexs.contains(index)) {
                    indexs.add(index);
                }
            }
            List<BaseDeptInfo> resultDept = new ArrayList<>();
            for (Integer i = 0; i < baseDeptInfos.size(); i++) {
                if (indexs.contains(i)) {
                    resultDept.add(baseDeptInfos.get(i));
                }
            }
            List<ScreenCheckDetailVO> result = getPersonForScreenCheck(resultDept, dutyScheduleInfoTimeDTO, customId);
            return result;
        } else {
            baseDeptInfos = baseDeptInfos.stream().filter(i -> i.getDeptName() != null).filter(distinctByKey(i -> i.getDeptName())).collect(Collectors.toList());
            DutyScheduleInfoTimeDTO dutyScheduleInfoTimeDTO = dutyScheduleInfoService.nowUser(customName).getData();
            List<BaseDeptInfo> resultDept = baseDeptInfos;
            List<ScreenCheckDetailVO> result = getPersonForScreenCheck(resultDept, dutyScheduleInfoTimeDTO, customId);
            return result;
        }
    }

    @Override
    public List<ScreenCheckTopic> questionList() {
        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        String customId = userInfoDetailVO.getCustomscode();
        List<ScreenCheckTopic> screenCheckTopics = screenCheckTopicRepository.list(new LambdaQueryWrapper<ScreenCheckTopic>()
                .eq(ScreenCheckTopic::getCustomId, customId)
                .orderByAsc(ScreenCheckTopic::getSort));
        screenCheckTopics.stream().forEach(i -> i.setDisable(true));
        return screenCheckTopics;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void questionsSave(ScreenCheckTopicSaveDTO screenCheckTopicSaveDTO) {
        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        String customId = userInfoDetailVO.getCustomscode();
        if (!CollectionUtils.isEmpty(screenCheckTopicSaveDTO.getScreenCheckTopicDetailSaveDTOList())) {
            screenCheckTopicSaveDTO.setScreenCheckTopicDetailSaveDTOList(screenCheckTopicSaveDTO.getScreenCheckTopicDetailSaveDTOList()
                    .stream().filter(distinctByKey(i -> i.getQuestionTitle()))
                    .collect(Collectors.toList()));

            List<ScreenCheckTopic> screenCheckTopics = new ArrayList<>();
            for (int i = 0; i < screenCheckTopicSaveDTO.getScreenCheckTopicDetailSaveDTOList().size(); i++) {
                ScreenCheckTopicDetailSaveDTO screenCheckTopicDetailSaveDTO =
                        screenCheckTopicSaveDTO.getScreenCheckTopicDetailSaveDTOList().get(i);
                ScreenCheckTopic screenCheckTopic = new ScreenCheckTopic();
                screenCheckTopic.setSort(i + 1);
                BeanUtils.copyProperties(screenCheckTopicDetailSaveDTO, screenCheckTopic);
                screenCheckTopic.setCustomId(customId);
                screenCheckTopic.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                screenCheckTopics.add(screenCheckTopic);
            }
            screenCheckTopicRepository.remove(new LambdaQueryWrapper<ScreenCheckTopic>()
                    .eq(ScreenCheckTopic::getCustomId, customId)
            );
            screenCheckTopicRepository.saveBatch(screenCheckTopics);
        }
    }

    @Override
    public Object delete(ScreenCheckDeleteDTO screenCheckDeleteDTO) {
        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        repository.update(new LambdaUpdateWrapper<ScreenCheck>()
                .eq(ScreenCheck::getId, screenCheckDeleteDTO.getId())
                .set(ScreenCheck::getDelFlag, DeleteFlagEnum.IS_DELETE.getValue())
                .set(ScreenCheck::getUpdateBy, userInfoDetailVO.getUserId())
                .set(ScreenCheck::getUpdateTime, LocalDateTime.now()));
        return true;
    }

    @Override
    public Object getThisCustomResult(String customId) {
        List<ScreenCheck> screenChecks;
        if (StringUtils.isEmpty(customId)) {
            screenChecks = screenCheckRepository.list(
                    new LambdaQueryWrapper<ScreenCheck>()
                            .eq(ScreenCheck::getBatchNum, "0")
                            .isNull(ScreenCheck::getCustomId)
            );
        } else {
            screenChecks = screenCheckRepository.list(
                    new LambdaQueryWrapper<ScreenCheck>()
                            .eq(ScreenCheck::getBatchNum, "0")
                            .eq(ScreenCheck::getCustomId, customId)
            );
        }
        List<JSONObject> result = new ArrayList<>();
        for (ScreenCheck screenCheck : screenChecks) {
            JSONObject jsonObject = new JSONObject(new LinkedHashMap<>());
            jsonObject.put("customName", screenCheck.getCustomName());
            jsonObject.put("checkTime", screenCheck.getCheckTime());
//            jsonObject=JSONObject.parseObject(JSONObject.toJSONString(screenCheck));
            List<ScreenCheckDetail> screenCheckDetails = screenCheckDetailRepository
                    .list(new LambdaUpdateWrapper<ScreenCheckDetail>()
                            .eq(ScreenCheckDetail::getCheckId, screenCheck.getId()));
            for (ScreenCheckDetail screenCheckDetail : screenCheckDetails) {
                jsonObject.put(screenCheckDetail.getQuestionTitle(), screenCheckDetail.getResultValue());
            }
            jsonObject.put("dutyPerson", screenCheck.getDutyPerson());
            jsonObject.put("checkPerson", screenCheck.getCheckPerson());
            jsonObject.put("reason", screenCheck.getReason());
            jsonObject.put("remark", screenCheck.getRemark());
            List<ScreenCheckDetail> resultvalue = screenCheckDetailRepository
                    .list(new LambdaUpdateWrapper<ScreenCheckDetail>()
                            .eq(ScreenCheckDetail::getCheckId, screenCheck.getId())
                            .eq(ScreenCheckDetail::getResultValue, "0"));
            jsonObject.put("failCount", "错" + resultvalue.size() + "个");
            result.add(jsonObject);
        }
        return result;
    }

    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        ConcurrentHashMap<Object, Boolean> map = new ConcurrentHashMap<>();
        return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    private List<ScreenCheckDetailVO> getPersonForScreenCheck(List<BaseDeptInfo> resultDept, DutyScheduleInfoTimeDTO hzDTO, String customId) {
        List<DutyScheduleInfo> dutyScheduleInfos = dutyScheduleInfoRepository.list(
                new LambdaQueryWrapper<DutyScheduleInfo>()
                        .in(DutyScheduleInfo::getCustomId, resultDept.stream().map(i -> i.getId()).collect(Collectors.toList()))
                        .lt(DutyScheduleInfo::getDStartDateTime, LocalDateTime.now())
                        .ge(DutyScheduleInfo::getDEndDateTime, LocalDateTime.now())
                        .in(DutyScheduleInfo::getDUserjob, "科员", "科领导"));
        if (CollectionUtils.isEmpty(dutyScheduleInfos)) {
            dutyScheduleInfos = dutyScheduleInfoRepository.list(
                    new LambdaQueryWrapper<DutyScheduleInfo>()
                            .in(DutyScheduleInfo::getCustomId, resultDept.stream().map(i -> i.getId()).collect(Collectors.toList()))
                            .eq(DutyScheduleInfo::getDDay, LocalDate.now())
                            .in(DutyScheduleInfo::getDUserjob, "科员", "科领导")
                            .orderByAsc(DutyScheduleInfo::getDStartDateTime));
        }
        Map<String, List<DutyScheduleInfo>> dutyScheduleMaps = dutyScheduleInfos.stream()
                .collect(Collectors.groupingBy(i -> i.getCustomId()));
        List<ScreenCheckDetailVO> screenCheckDetailVOS = resultDept.stream().map(i -> {
            ScreenCheckDetailVO screenCheckDetailVO = new ScreenCheckDetailVO();
            BeanUtils.copyProperties(i, screenCheckDetailVO);
            // 获取当前值班电话
            final String phoneTel = queryCurPhoneTel(i);
            screenCheckDetailVO.setPhoneTel(phoneTel);

            List<DutyScheduleInfo> mySchdules = dutyScheduleMaps.get(i.getId());
            if (!CollectionUtils.isEmpty(mySchdules)) {
                screenCheckDetailVO.setDutyPersonName(mySchdules.get(0).getDUsername());
                screenCheckDetailVO.setDutyPersonNo(mySchdules.get(0).getDUserno());
            }

            if (screenCheckDetailVO.getDutyPersonName() == null && screenCheckDetailVO.getDutyPersonNo() == null) {
                screenCheckDetailVO.setDutyPersonName("");
                screenCheckDetailVO.setDutyPersonNo("");
            }
            if (hzDTO != null && hzDTO.getKJInfo() != null) {
                screenCheckDetailVO.setHzPersonName(hzDTO.getKJInfo().getDUsername());
                screenCheckDetailVO.setHzPersonNo(hzDTO.getKJInfo().getDUserno());
            }
            List<ScreenCheckReason> screenCheckReasons;
            if (!StringUtils.isEmpty(customId)) {
                screenCheckReasons = screenCheckReasonRepository.list(new LambdaQueryWrapper<ScreenCheckReason>()
                        .eq(ScreenCheckReason::getCustomId, customId));
            } else {
                screenCheckReasons = screenCheckReasonRepository.list(new LambdaQueryWrapper<ScreenCheckReason>()
                        .eq(ScreenCheckReason::getCustomId, systemConfig.getZsCustomId()));
            }
            List<ScreenCheckTopic> screenCheckQuestions;
            if (!StringUtils.isEmpty(customId)) {
                screenCheckQuestions = screenCheckTopicRepository.list(new LambdaQueryWrapper<ScreenCheckTopic>()
                        .eq(ScreenCheckTopic::getCustomId, customId));
            } else {
                screenCheckQuestions = screenCheckTopicRepository.list(new LambdaQueryWrapper<ScreenCheckTopic>()
                        .eq(ScreenCheckTopic::getCustomId, systemConfig.getZsCustomId()));
            }
            screenCheckDetailVO.setScreenCheckReasons(screenCheckReasons);
            screenCheckDetailVO.setScreenCheckTopics(screenCheckQuestions);
            return screenCheckDetailVO;
        }).collect(Collectors.toList());
        return screenCheckDetailVOS;
    }

    /**
     * 获取当前时刻的值班电话
     * @param i 部门信息
     * @return 值班电话
     */
    private String queryCurPhoneTel(BaseDeptInfo i) {
        final LocalDateTime now = LocalDateTime.now();
        final STypeEnum sTypeEnum = paramHolidaysRepository.deriveCurSType(i.getId(), now);
        final BaseCustomPhone baseCustomPhone = baseCustomPhoneRepositoy.queryCurRecord(
                i.getId(), sTypeEnum.getCode(), now, SettingModeEnum.SETTINGS_PAGE.getCode());
        return null != baseCustomPhone ? baseCustomPhone.getPhoneTel() : StringUtils.EMPTY;
    }


    /**
     * 判断是白天还是夜间节假日
     */
    public String dayOrNight(String customId) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startTime = LocalDateTime.now().withHour(8).withMinute(30);
        LocalDateTime enfTime = LocalDateTime.now().withHour(17).withMinute(30);
        ParamHolidays paramHolidays = paramHolidaysRepository.getOne(new LambdaQueryWrapper<ParamHolidays>()
                .eq(ParamHolidays::getHolidayDate, now.toLocalDate())
                .eq(ParamHolidays::getCustomId, customId), false
        );
        if (paramHolidays != null) {
            return "3";
        }
        if (now.isAfter(startTime) || now.equals(startTime) && now.isBefore(enfTime)) {
            return "2";
        } else {
            return "3";
        }

    }


}
